﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using BrainTechLLC.ThreadSafeObjects;
using System.Runtime.Serialization;
#if USE_HYPER
using Hyper.ComponentModel;
#endif

namespace BrainTechLLC
{	
    // UNUSED - does not implement interface IEventPerceiver - todo: move this code elsewhere
	public class EventPerceiver
	{
		public long AssociatedID { get; set; }

		public static INotificationMessage PerceiveEvent(long id, IEventPerceiver perceiver, IEventToPerceive eventInfo)
		{
			IEvent evt = eventInfo.GetPerceivedEvent(perceiver);

			if (evt == null || evt.EventData == null)
				return null;

			if (typeof(string).IsAssignableFrom(evt.EventData.GetType()))
			{
				string s = evt.EventData.ToString();
				if (s.Contains("~target"))
				{
                    if (!eventInfo.HasTargets)
                    {
                        throw new Exception("Event string " + s + " specified ~target, but no targets specified in event.");
                    }

                    BaseClass nameAndDesc = eventInfo.Targets.AllIDs[0].Find() as BaseClass;
                    IViewOfThing targetView = nameAndDesc.GetViewWhenObservedBy(perceiver, evt.ViewType);
					s = s.Replace("~target", targetView.ViewedProperties["ShortName"].GetPropertyValue(evt.ViewType, true).ToString());
				}
				if (s.Contains("~source"))
				{
					s = s.Replace("~source", eventInfo.Sources.AllIDs[0].ToString());
				}
				return new Notification(s);
			}
			return new Notification(evt.EventData);
		}

		public static bool CanPerceive(IEventToPerceive eventInfo, ViewType view)
		{
			return true;
		}
	}

    public static class Ex
    {
        public static object GetPropertyValue(this List<IViewedProperty> list, ViewType type, bool returnEmptyStringIfNull)
        {
            if (list == null)
                return returnEmptyStringIfNull ? string.Empty : null;

            IViewedProperty prop = list.GetProperty(type);

            if (prop == null)
                return returnEmptyStringIfNull ? string.Empty : null;

            if (prop.Value == null)
                return returnEmptyStringIfNull ? string.Empty : null;

            return prop.Value.Value;
        }

        public static IViewedProperty GetProperty(this List<IViewedProperty> list, ViewType type)
        {
            if (list == null)
                return null;

            for (int n = 0; n < list.Count; n++)
            {
                var prop = list[n];

                if (prop.ViewType == type)
                    return prop;
            }

            return null;
        }
    }
}